<template>
  <header class="header-box">
    <div class="text">
      <div class="time">
        <span>{{ time.day }}</span>
        <span>{{ time.month }}</span>
      </div>
      <h2 class="title">知乎日报</h2>
    </div>

    <div class="picture">
      <router-link to="/person">
        <img :src="pic" alt="" class="logo" />
      </router-link>
    </div>
  </header>
</template>

<script>
import { computed, onBeforeMount } from "vue";
import { useStore } from "vuex";
import { formatTime } from "@/assets/utils";
import timg from "@/assets/images/timg.jpg";

export default {
  name: "HomeHead",
  props: {
    today: {
      type: String,
      required: true,
    },
  },
  setup(props) {
    const store = useStore();

    // 创建计算属性「ComputedRefImpl对象」：获取想要的日和月
    let time = computed(() => {
      let today = props.today;
      let [month, day] = formatTime(today, "{1}-{2}").split("-");
      let arr = [
        "",
        "一月",
        "二月",
        "三月",
        "四月",
        "五月",
        "六月",
        "七月",
        "八月",
        "九月",
        "十月",
        "十一月",
        "十二月",
      ];
      return {
        month: arr[+month],
        day,
      };
    });

    // 创建计算属性：根据vuex中的登录信息，控制显示的头像
    let pic = computed(() => {
      let { info } = store.state;
      return info ? info.pic : timg;
    });

    // 在组件第一次渲染的时候，我们需要观察vuex中的isLogin值，如果还是null，说明不知道是不是登录了，此时我们派发任务校验一下
    onBeforeMount(() => {
      let { isLogin } = store.state;
      if (isLogin === null) store.dispatch("changeIsLoginAsync");
    });

    return {
      time,
      pic,
    };
  },
};
</script>

<style lang="less" scoped>
.header-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;

  .picture {
    box-sizing: border-box;
    width: 34px;
    height: 34px;
    border-radius: 50%;
    overflow: hidden;

    a {
      display: block;
      height: 100%;

      .logo {
        display: block;
        width: 100%;
        height: 100%;
      }
    }
  }

  .text {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    height: 34px;

    .title {
      padding-left: 20px;
      line-height: 68px;
      font-size: 44px;
      border-left: 1px solid #ddd;
      transform: scale(0.5);
      transform-origin: left;
    }

    .time {
      box-sizing: border-box;
      padding-right: 15px;

      span {
        display: block;
        line-height: 20px;
        font-size: 20px;
        text-align: center;

        &:nth-last-child(1) {
          line-height: 14px;
          font-size: 12px;
        }
      }
    }
  }
}
</style>